<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>home</title>
    <link rel="stylesheet" th:href="@{/static/lib/layui-v2.5.4/css/layui.css}" media="all">
    <script>
        const PATH = "[[${#httpServletRequest.getContextPath()}]]";
    </script>

    <!-- 避免Thymeleaf异常 -->
    <script type="text/javascript" th:inline="javascript"></script>

    <script type="text/html" id="control">
        <a class="layui-btn layui-btn-xs" lay-event="detail">详情</a>
    </script>
</head>
<body id="iosiframe">

<div id='head_div'>
    <input class="layui-hide" id="environment" value="ENVIRONMENT_ALL">
    <div class="layui-form layui-form-pane" action="" onsubmit="return false">
        <div class="layui-form-item">
            <label class="layui-form-label" title="起始时间"><span style="color:red;">*</span>起始时间</label>
            <div class="layui-input-block">
                <input type="text" id="time" class="layui-input" onchange="getEnv();">
            </div>
        </div>

        <div class="layui-form-item">
            <!--<div class="layui-inline">
                <label class="layui-form-label">环境</label>
                <div class="layui-input-inline">
                    <select id="environment">
                        <option value="ENVIRONMENT_ALL">ALL</option>
                    </select>
                </div>
            </div>-->

            <div class="layui-inline">
                <label class="layui-form-label" title="服务器主机名" style="padding: 8px 0;">服务器主机名</label>
                <div class="layui-input-inline">
                    <select id="host">
                        <option value="">请选择服务器主机名</option>
                    </select>
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label" title="探针类型">探针类型</label>
                <div class="layui-input-inline">
                    <select id="agentName">
                        <option value="">请选择探针类型</option>
                    </select>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn2" id="search" onclick="showData(1)">搜索</button>
    </div>
</div>
<div id='body_div'>
    <table class="layui-table" id='data-table' lay-filter="control"></table>
</div>

<script src="/static/layui/layui.all.js" th:src="@{/static/lib/layui-v2.5.4/layui.all.js}"></script>
<script>
    let $, table, form, layer, laydate, tableHeight = 100;
    layui.use(['layer', 'table', 'form'], function () {
        $ = layui.jquery, table = layui.table, form = layui.form, layer = layui.layer, laydate = layui.laydate;
        laydate.render({
            elem: '#time'
            , type: 'datetime'
            , range: true
            // , format: 'yyyy-MM-ddTHH:mm:ss.SSSZ'
            , format: 'yyyy-MM-dd HH:mm:ss'
            , done: function (time) {
                if (time === '') {
                    return false;
                }
                let start, end;

                time = time.split(' - ');
                if (time != null && time.length === 2) {
                    start = time[0].replace(' ', 'T') + '.000Z';
                    end = time[1].replace(' ', 'T') + '.000Z';
                }
                $.post({
                    url: '/services/getEnv',
                    data: {
                        start: encodeURIComponent(start),
                        end: encodeURIComponent(end)
                    },
                    success: function (res) {
                        if (res.success) {
                            $("#environment").html("<option value='ENVIRONMENT_ALL'>ALL</option>");
                            let data = res.data;
                            data = data.replace('[', '').replace(']', '').replaceAll('\"', '').replaceAll('\'', '');
                            data = data.split(',');
                            if (data.length > 0) {
                                for (let i in data) {
                                    if (data.hasOwnProperty(i)) {
                                        $("#environment").append(new Option(data[i], data[i]));
                                    }
                                }
                                getParam();
                            }
                            form.render();
                        }
                    }
                });
            }
        });
    });
</script>
<script type="text/javascript" th:inline="none">
    function showData() {
        init();
        let time = $("#time").val();
        if (time === '') {
            layer.msg('请选择起始时间!', {icon: 2});
            return false;
        }
        let start, end;
        time = time.split(' - ');
        if (time != null && time.length === 2) {
            start = time[0].replace(' ', 'T') + '.000Z';
            end = time[1].replace(' ', 'T') + '.000Z';
        }

        let host = $("#host").val();
        let agentName = $("#agentName").val();
        let environment = $("#environment").val();

        let hosts = [];
        hosts.push(host);
        let agentNames = [];
        agentNames.push(agentName);
        let uiFilters = {
            environment: environment
        };

        if (host !== '') {
            uiFilters['host'] = hosts;
        }

        if (agentName !== '') {
            uiFilters['agentName'] = agentNames;
        }
        $.post({
            url: '/services/list',
            data: {
                start: encodeURIComponent(start),
                end: encodeURIComponent(end),
                uiFilters: encodeURIComponent(JSON.stringify(uiFilters))
            },
            success: function (res) {
                let data = [];
                if (res.success) {
                    if (res.data.items === '') {
                        data = [];
                    } else {
                        data = res.data.items;
                    }
                }
                table.render({
                    elem: '#data-table',
                    data: data,
                    cellMinWidth: 80,
                    height: tableHeight,
                    totalRow: false,
                    cols: [[
                        {
                            field: '', title: '#', align: 'center', width: 110, sort: false, templet: function (r) {
                                return r.LAY_INDEX;
                            }
                        }
                        , {field: 'healthStatus', title: '状态', align: 'center', width: 110, sort: true}
                        , {field: 'serviceName', title: '应用名称', align: 'center', width: 125, sort: true}
                        // , {field: 'environments', title: '环境', align: 'center', sort: true}
                        , {
                            field: '', title: '延迟(平均值)', align: 'center', sort: true, templet: function (r) {
                                return (Number(r['avgResponseTime']['value']) / 1000).toFixed(1) + ' ms';
                            }
                        }, {
                            field: '', title: '吞吐量(平均值)', align: 'center', sort: true, templet: function (r) {
                                let val = Number(r['transactionsPerMinute']['value']).toFixed(6);
                                if (Number(fix(val, 2)) < 0.1) {
                                    return "< 0.1 tpm";
                                } else {
                                    return fix(val, 2) + " tpm";
                                }
                            }
                        }, {
                            field: '', title: '错误率', align: 'center', sort: true, templet: function (r) {
                                return (Number(r['transactionErrorRate']['value']) * 100).toFixed(0).toString() + '%';
                            }
                            /*}, {
                                field: 'control',
                                fixed: "right",
                                unresize: true,
                                width: 120,
                                title: "操作",
                                align: "center",
                                toolbar: "#control"*/
                        }
                    ]],
                    id: 'data-table',
                    page: true,
                    limits: [15, 30, 50, 100],
                    limit: 15,
                    even: true
                });
            }
        });
    }

    function fix(num, decimal) {
        num = num.toString();
        let index = num.indexOf('.');
        if (index !== -1) {
            num = num.substring(0, decimal + index + 1)
        } else {
            num = num.substring(0)
        }
        return parseFloat(num).toFixed(decimal)
    }

    /**
     * 获取环境列表
     * @returns
     */
    function getEnv() {
        let time = $("#time").val();
        if (time === '') {
            layer.msg('请选择起始时间!', {icon: 2});
            return false;
        }
        let start, end;

        time = time.split(' - ');
        if (time != null && time.length === 2) {
            start = time[0].replace(' ', 'T') + '.000Z';
            end = time[1].replace(' ', 'T') + '.000Z';
        }
        $.post({
            url: '/services/getEnv',
            data: {
                start: encodeURIComponent(start),
                end: encodeURIComponent(end)
            },
            success: function (res) {
                console.log(res);
            }
        });
    }

    /**
     * 获取服务、探针列表
     */
    function getParam() {
        let time = $("#time").val();
        if (time === '') {
            return false;
        }
        let start, end;
        time = time.split(' - ');
        if (time != null && time.length === 2) {
            start = time[0].replace(' ', 'T') + '.000Z';
            end = time[1].replace(' ', 'T') + '.000Z';
        }
        let environment = $("#environment").val();
        let uiFilters = {environment: environment};

        $.post({
            url: '/services/getParam',
            data: {
                start: start,
                end: end,
                uiFilters: encodeURIComponent(JSON.stringify(uiFilters)),
                filterNames: encodeURIComponent('["host","agentName"]')
            },
            success: function (res) {
                if (res.success) {
                    let data = res.data;
                    $("#host").html("<option value=''>请选择服务器主机名</option>");
                    $("#agentName").html("<option value=''>请选择探针类型</option>");
                    if (data.length > 0) {
                        for (let i in data) {
                            if (data.hasOwnProperty(i)) {
                                let temp = data[i];
                                let ops = temp['options'];
                                if (temp['name'] === 'host') {
                                    if (ops.length > 0) {
                                        for (let o in ops) {
                                            if (ops.hasOwnProperty(o)) {
                                                $("#host").append(new Option(ops[o]['name'] + "(" + ops[o]['count'] + ")", ops[o]['name']))
                                            }
                                        }
                                    }
                                }
                                if (temp['name'] === 'agentName') {
                                    if (ops.length > 0) {
                                        for (let o in ops) {
                                            if (ops.hasOwnProperty(o)) {
                                                $("#agentName").append(new Option(ops[o]['name'] + "(" + ops[o]['count'] + ")", ops[o]['name']))
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    layui.form.render();
                }
            }
        });
    }

    function init() {
        let ua = navigator.userAgent.toLowerCase();
        let screenWidth = window.screen.width;
        if (!/iphone|ipad|ipod/.test(ua)) {
            $("#iosiframe").attr("scrolling", "auto");
        } else {
            $('#iosiframe').width(screenWidth + 'px');
        }

        $("body").css({
            "height": $(window).height() - 15
        });
        $("#body_div").css({
            "height": $("body").height() - $("#head_div").height() - 10
        });
        tableHeight = $("#body_div").height() - 15;
    }

    $(window).resize(function () {
        init();
    });
</script>
</body>
</html>
